package belajarzk.action.maintenance;

import java.util.Locale;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.zkoss.web.Attributes;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericAutowireComposer;
import org.zkoss.zul.Label;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import belajarzk.common.Common;
import belajarzk.database.hibernate.HibernateUtil;
import belajarzk.database.model.Tbmuser;


public class LoginAction extends GenericAutowireComposer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 187958355469811830L;
	private Textbox username;
	private Textbox password;

	private Label pengguna;
	private Label kataSandi;

	private Window mainWindow;

	@Override
	public void doAfterCompose(Component comp) throws Exception {
		// TODO Auto-generated method stub
		super.doAfterCompose(comp);
		// session.setAttribute(Attributes.PREFERRED_LOCALE,
		// new Locale("in", "ID"));
		// session.setAttribute("users", null);
		username.select();
		username.setFocus(true);

		pengguna.setValue("Pengguna");
		kataSandi.setVisible(true);
		password.setVisible(true);

		username.focus();
	}

	public void onLogin(Event event) throws Exception {

		session.setAttribute(Attributes.PREFERRED_LOCALE,
				new Locale("in", "ID"));
		Session ses = HibernateUtil.currentSession();

		Criteria criteria = ses.createCriteria(Tbmuser.class);
		criteria.setProjection(Projections.count("id"));
		criteria.add(Restrictions.eq("userId", username.getValue().trim()));
		criteria.add(Restrictions
				.eq("userPassword", password.getValue().trim()));
		Number result = ((Number) criteria.uniqueResult());
		Boolean hasil = (result == null ? new Integer(0) : result).intValue() != 0;
		if (hasil) {
			criteria = ses.createCriteria(Tbmuser.class);
			criteria.add(Restrictions.eq("userId", username.getValue().trim()));
			criteria.add(Restrictions.eq("userPassword", password.getValue()
					.trim()));
			Tbmuser users = ((Tbmuser) criteria.uniqueResult());
			session.setAttribute("users", null);
			session.setAttribute("usersTemp", users);
			Common.realodBahasa();
			execution.sendRedirect("main/main.zul");
		} else {
			Messagebox
					.show(
							"Nama pengguna atau password yang anda masukkan tidak sesuai",
							"Peringatan", 1, Messagebox.INFORMATION);
			session.setAttribute("users", null);
		}
	}

}
